import 'package:blog/screens/components/article_item.dart';
import 'package:blog/screens/components/articles_container.dart';
import 'package:blog/tools/build.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../api/api.dart';
import '../locator.dart';
import '../constants.dart';
import '../src/generated/models/article.pb.dart';
import 'components/layout/footer.dart';
import 'components/layout/header.dart';
import 'components/layout/side_menu.dart';

class SearchScreen extends StatefulWidget {
  const SearchScreen({Key? key}) : super(key: key);

  @override
  State<SearchScreen> createState() => _SearchScreenState();
}

class _SearchScreenState extends State<SearchScreen> {
  late List<ArticleItem> _articles = [];
  String keyword = '';

  Future<List<ArticleItem>> getArticleList() async {
    var params = Get.parameters;
    keyword = params['keyword'] ?? '';
    _articles = await locator<Api>()
        .getArticleItem(page: 1, pageSize: 20, filter: params);
    return _articles;
  }

  Widget buildContent() {
    if (_articles.isEmpty) {
      return Text("没有相关的文章");
    }
    Map<String, String>filter = {};
    Get.parameters.forEach((key, value){
        filter.addIf(value != null, key, value ?? '');
    });
    return ArticlesContainer(articles: _articles, filter:filter);
  }

  Widget buildScreenContent() {
    return Scaffold(
      drawer: SideMenu(),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Header(),
            Container(
              padding: EdgeInsets.all(kDefaultPadding),
              constraints: BoxConstraints(maxWidth: kMaxWidth,maxHeight: 2000),
              child: SafeArea(child: buildContent()),
            ),
            Footer(),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
        future: getArticleList(),
        builder: BuilderTool.futureBuild((data) => buildScreenContent()));
  }
}
